package com.ruoyi.mall.app.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.app.service.IDtsUserService;
import com.ruoyi.mall.common.domain.DtsUser;
import org.apache.coyote.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.sql.Date;

@RestController
@RequestMapping("/api/logins/wechat/login")
public class DtsLoginController {

    @Value("${wechat.app-id}")
    private String appId; // 微信小程序 AppID（需从配置文件获取）

    @Value("${wechat.app-secret}")
    private String appSecret; // 微信小程序 AppSecret（需从配置文件获取）

    private final IDtsUserService userService; // 用户服务

    public DtsLoginController(IDtsUserService userService) {
        this.userService = userService;
    }

    @PostMapping
    public AjaxResult wechatLogin(@RequestBody JSONObject request , HttpServletRequest httpServletRequest) {
        String code = request.getString("code"); // 前端传递的登录凭证
        String nickname = request.getString("nickname"); // 微信昵称（注意字段名与前端一致）
        String avatar = request.getString("avatarUrl"); // 微信头像

        // 获取客户端 IP 地址
        String clientIp = getClientIpAddress(httpServletRequest);
        System.out.println("客户端 IP 地址: " + clientIp);

        System.out.println("接收到的参数：code=" + code + ", nickname=" + nickname + ", avatar=" + avatar);
        // 1. 调用微信接口换取 openid
        String openid = this.getOpenidFromWeChat(code);
        if (openid == null) {
            return AjaxResult.error("微信登录失败");
        }

        // 2. 查询或创建用户（基于 DtsUser.java 中的 weixinOpenid 字段）
        DtsUser user = userService.getByWeixinOpenid(openid);
        if (user == null) {
            user = new DtsUser();
            user.setUsername("随机生成"+System.currentTimeMillis());
            user.setPassword("123456");
            user.setWeixinOpenid(openid);
            user.setNickname("随机生成"+System.currentTimeMillis()); // 存储昵称
            user.setAvatar(avatar); // 存储头像
            user.setUserLevel(0); // 默认普通用户
            user.setStatus(0); // 可用状态
            userService.insert(user); // 插入新用户
        } else {
            // 可选：更新用户信息（如头像、昵称）
            user.setNickname(nickname);
            user.setAvatar(avatar);
            userService.update(user);
        }

        // 3. 生成登录态（示例：返回用户 ID 或 JWT Token）
        return AjaxResult.success()
                .put("token", "Bearer_" + user.getId()) // 简化版 token，实际需用 JWT
                .put("userInfo", user);
    }

    /**
     * 调用微信接口获取 openid
     */
    private String getOpenidFromWeChat(String code) {

        if (StringUtils.isEmpty(code)) {
            throw new IllegalArgumentException("无效的 code");
        }

        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" + appId +
                "&secret=" + appSecret +
                "&js_code=" + code +
                "&grant_type=authorization_code";

        String result = HttpUtil.get(url);
        JSONObject json = JSONObject.parseObject(result);
        if (json.containsKey("errcode")) {
            String errmsg = json.getString("errmsg");
            System.err.println("微信接口错误：" + errmsg);
            throw new RuntimeException("微信登录失败：" + errmsg);
        }
        System.out.println("微信接口返回: " + result);
        return json.getString("openid");
    }

    /**
     * 获取客户端 IP 地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader != null && !xffHeader.isEmpty()) {
            return xffHeader.split(",")[0].trim();
        }
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty()) {
            return xRealIp;
        }
        return request.getRemoteAddr();
    }

}




























